package com.lv.suyiyong.hfr.ui

import android.text.TextUtils
import android.view.KeyEvent
import android.widget.TextView
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.KeyboardUtils
import com.lv.common.base.BaseActivity
import com.lv.common.ktx.setSafeListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.*
import com.lv.service.bean.CardPageBean
import com.lv.common.bean.CommonSelectedBean
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.*
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.ClientsHFRAdapter
import com.lv.suyiyong.hfr.databinding.ActivitySearchClientBinding
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob

import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/4/12 2:04 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * 描述：找货大全 搜索
 */
@Route(path = ARoutUtils.ClientSearchActivity)
class ClientSearchActivity : BaseActivity<ActivitySearchClientBinding>() {
    @Autowired(name = "bindCard")
    @JvmField
    var mBindCard: String = ""//是否绑卡操作 不是空时为绑卡操作
    private val viewModule: ServiceViewModel by viewModel()
    private val mEditorViewModel by viewModels<EditorViewModel>()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private val mBeans = mutableListOf<CommonSelectedBean>()
    private var mPosition: Int = 0
    private var mCpName = ""
    private var UPDATED: Long = System.currentTimeMillis()
    private var mAdapter: ClientsHFRAdapter? = null
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private val paramsMap = mutableMapOf<String, String>()

    //    private var mDaySel = "0"//选择的日
    override fun getLayoutRes() = R.layout.activity_search_client
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@ClientSearchActivity, viewTop)
            ivBackTop.setOnClickListener { finish() }
            editorModel = mEditorViewModel
        }
    }


    override fun initConfig() {
        super.initConfig()

    }

    private fun initAdapter() {
        mAdapter = ClientsHFRAdapter(mBeans)
        mBinding.rvContent.adapter = mAdapter
    }

    private fun findMyTelCustomer() {

        paramsMap["year"] = "0"
        paramsMap["month"] = "0"
        lifecycleScope.launchWhenCreated {
//            val result: DataResult<BaseYgxRsp> =
//                myScope.async {
//                    viewModule.findMyTelCustomer(
//                        page,
//                        pageSize,
//                        UPDATED,
//                        paramsMap
//                    )
//                }.await()
//            parseResult(result)
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<CardPageBean> { code, data, message, result ->
                val items = data?.items
                if (!items.isNullOrEmpty()) {
//                        mBeans.addAll(items)
                    UPDATED = items[items.size - 1].updated ?: 0L
                }
//                MyUtils.recyclerviewSetData(
//                    page,
//                    pageSize,
//                    mBinding.refreshLayout,
//                    mBeans,
//                    items,
//                    mAdapter
//                )
//                mAdapter?.setEmptyView(getEmptyView(mBinding.rvContent))

            }
            onBizError<Any> { code, message, data ->
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.finishLoadMore()
                showToast(message)
            }
        }
        data.onFailure {
            mBinding.refreshLayout.finishRefresh()
            mBinding.refreshLayout.finishLoadMore()
        }
    }

    override fun initEvents() {
        super.initEvents()
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                UPDATED = System.currentTimeMillis()
                findMyTelCustomer()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                findMyTelCustomer()
            }
        })
//        mAdapter?.onViewItemClickListener = OnPositionTListener { position, data ->
//            mPosition = position
//            ARouter.getInstance().build(ARoutUtils.ClientCardActivity)
//                .withString("userid", data.userid)
//                .withString("userTxaccid", data.userTxaccid)
//                .withString("bindCard", mBindCard)
//                .navigation()
//            if (mBindCard.isNotEmpty()) {
//                finish()
//            }
//        }
        mBinding.tvSearch.setSafeListener {
            var cpName = mEditorViewModel.obCpname.get() ?: ""
            if (TextUtils.isEmpty(cpName)) {
                showToast("请输入要搜索的公司名称")
                mCpName = ""
                return@setSafeListener
            }
            if (cpName != mCpName) {
                mCpName = cpName
                paramsMap["name"] = cpName
                findMyTelCustomer()
            }
        }
        mBinding.etSearch.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                KeyboardUtils.hideSoftInput(mBinding.etSearch)
                var cpName = mEditorViewModel.obCpname.get() ?: ""
                if (TextUtils.isEmpty(cpName)) {
                    showToast("请输入要搜索的公司名称")
                    mCpName = ""
                    return false
                }
                if (cpName != mCpName) {
                    mCpName = cpName
                    paramsMap["name"] = cpName
                    findMyTelCustomer()
                    return true
                } else {
                    return false
                }
            }
        })
    }


    override fun initData() {
        super.initData()
        initAdapter()

    }


}